<?php

/**
 * 自动生成 MerContentService
 * 
 * Apps/Common/Service/MerContentService.class.php
 * Zix @ 2015-06-15
 */

namespace Common\Service;

class MerContentService {

  private static $instance;

  public static function instance() {
    if (self::$instance == null) {
      $instance = new MerContentService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'mer_id' => 0 ,
      'catalog' => 0 ,
      'sort' => 99 ,
      'title' => '',
      'icon' => '',
      'tag' => '',
      'desc' => '',
      'content' => '',
      'status' => 0 ,
      'create_date' => date('Y-m-d H:i:s'),
      'update_date' => date('Y-m-d H:i:s'),
    );
  }

  function get_by_id($id) {
    $Mercontent = M('MerContent');
    $data = $Mercontent->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'page' => 1,
      'page_size' => 6,
      'mer_id' => 0 ,
      'status' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $Mercontent = M('MerContent');

    $where = array();

    if (!empty($config['status'])) {
      $where['mc.status'] = $config['status'];
    }
    
    if (!empty($config['mer_id'])) {
      $where['mc.mer_id'] = $config['mer_id'];
    }

    if ($config['count']) {
      return $Mercontent->alias('mc')->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $Mercontent
          ->alias('mc')
          ->field('mc.* , md.text as catalog_text')
          ->join('mer_Dictionary md on md.id = mc.catalog')
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $Mercontent->_sql();
      return $data ? $data : array();
    }
  }

  function create($data) {
    $Mercontent = M('MerContent');
    $ret = $Mercontent->add($data);
    if ($ret) {
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function update($id, $data) {
    $Mercontent = M('MerContent');

    $ret = $Mercontent->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $Mercontent = M('MerContent');
    $ret = $Mercontent->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }

}
